/* Snow in Canvas
 * (c) 2009 by Hay Kranen <http://www.haykranen.nl/projects/snowcanvas>
 * Released under the MIT / X11 license, see <http://www.opensource.org/licenses/mit-license.php>
 */
function init() {
    var MIN_SPEED = 3,
        MAX_SPEED = 15,
        MIN_PIXEL_SIZE = 3,
        MAX_PIXEL_SIZE = 10,
        FLAKES = 100,
        FPS = 50,
        flakes = [];

    var canvas = document.createElement('canvas');
    if (typeof G_vmlCanvasManager != "undefined") {
        // Initialize excanvas for IE
        G_vmlCanvasManager.initElement(canvas);
    }
    document.body.appendChild(canvas);

    // Set to width and height of screen, using a hack for IE
    canvas.width  = (typeof window.innerWidth == "number")
                    ? window.innerWidth
                    : document.documentElement.clientWidth;
    canvas.height = (typeof window.innerHeight == "number")
                    ? window.innerHeight
                    : document.documentElement.clientHeight;

    var ctx = canvas.getContext('2d');
    ctx.fillStyle = "rgb(255, 0, 0)";

    function rand(a, b) {
        var max = a || b;
        var min = b || 0;

        return Math.floor(Math.random() * (max - min)) + min;
    }

    function particle(f) {
        ctx.fillStyle = "rgba(" + f.c + "," + f.c + "," + f.c + ", " + f.a + ")";
        ctx.beginPath();
        ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fill();
    }

    // Set up snow lookup table
    for (var i = 0; i < FLAKES; i++) {
        flakes[i] = {
            "x" : rand(canvas.width),
            "y" : rand(canvas.height),
            "c" : rand(50, 255),
            "s" : rand(MIN_SPEED, MAX_SPEED),
            "r" : rand(MIN_PIXEL_SIZE, MAX_PIXEL_SIZE),
            "a" : Math.random()
        };

        var f = flakes[i];
        particle(f);
    }

    function snow() {
        // Clear the field
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (var i = 0; i < FLAKES; i++) {
            var f = flakes[i];

            // x or y out of bounds
            if (f.x > canvas.width || f.x < 0 || f.y > canvas.height) {
                f.y = 0;
                f.x = rand(canvas.width);
            }

            f.y += f.s;
            f.x += (Math.sin(i) * f.r);

            // Draw
            particle(f);
        }

        setTimeout(snow, FPS);
    }

    snow();
}